<script setup>
import { Modal } from 'ant-design-vue'
import { CaretDownFilled, CheckCircleOutlined, ColumnHeightOutlined, DeleteOutlined, DoubleRightOutlined, DownOutlined, EditOutlined, KeyOutlined, LockOutlined, PlusOutlined, ReloadOutlined, SearchOutlined, SettingOutlined, UndoOutlined, UpOutlined } from '@ant-design/icons-vue'
import { getCardTotalFee, getMerchantList } from '~@/api/card/index'
import { getRechargeList } from '~@/api/order/index'

defineOptions({
  name: 'SourceCard',
})
// 新增角色
const roleForm = ref()
const userTitle = shallowRef('')
const cardOpen = ref(false)

const editInfo = reactive({
  roleId: null,
})
const totalInfo = shallowRef({
  batchSum: 0,
  totalSum: 0,
  storageSum: 0,
})

const confirmLoading = ref(false) // 确认加载中

const dataInfo = reactive({
  roleId: null,
})

const options = ref([])
const saleOptions = ref([])

const statusOptions = ref([
  {
    value: '',
    label: '全部',
  },
  {
    value: 'INIT',
    label: '库存',
  },
  {
    value: 'ACTIVE',
    label: '已登记',
  },
])
const formState = reactive({
  cardType: '',
  faceAmount: '',
  total: '',
  useAppIdList: [],
  batchIntro: '',
})
const salesState = reactive({
  cardNo: '',
  status: '',

})
const giftInfo = reactive({
  remarks: '',
})

const message = useMessage()
const selectedRowKeys = shallowRef([])

const columns = shallowRef([
  {
    title: '充值渠道',
    dataIndex: 'subAppName',
    width: 200,
    ellipsis: true,
  },
  {
    title: '卡号',
    dataIndex: 'cardNo',
    width: 200,
  },

  {
    title: '持卡人姓名',
    dataIndex: 'userName',
    width: 150,

  },
  {
    title: '支付方式',
    dataIndex: 'channelName',
    width: 200,

  },
  {
    title: '充值金额',
    dataIndex: 'rechargeFee',
    width: 120,

  },
  {
    title: '充值时间',
    dataIndex: 'rechargeCompleteTime',
    width: 200,
    customRender: ({ text }) => {
      if (text) {
        return text
      }
      else {
        return '--'
      }
    },

  },
])

const loading = shallowRef(false)
const totalNum = shallowRef(0)
const totalDetailNum = shallowRef(0)
const pagination = reactive({
  pageSize: 8,
  pageSizeOptions: ['10', '20', '30', '40'],
  current: 1,
  total: totalNum,
  showSizeChanger: true,
  // showQuickJumper: true,
  showTotal: total => `总共：${total}`,
  onChange(current, pageSize) {
    pagination.pageSize = pageSize
    pagination.current = current
    init()
  },
})
const dataSource = shallowRef([])
const formModel = reactive({
  tradeDate: void 0,
  subAppId: void 0,
})
const tableSize = ref(['large'])
const open = ref(false)

const dropdownVisible = ref(false)
const getCheckList = computed(() => columns.value.map(item => item.dataIndex))
onMounted(() => {
  init()
  getAppName()
  getTotal()
})

// 获取医院名称
async function getAppName() {
  const { data } = await getMerchantList()
  const appData = data?.map(item => ({
    value: item.appId,
    label: item.appName,
  }))
  options.value = appData
};

// 获取统计信息
async function getTotal() {
  const startTime = formModel.tradeDate?.[0]?.format('YYYY-MM-DD')
  const endTime = formModel.tradeDate?.[1]?.format('YYYY-MM-DD')
  const { data } = await getCardTotalFee({ ...formModel, startTime, endTime })
  totalInfo.value = data
};

async function init() {
  if (loading.value)
    return
  loading.value = true
  try {
    const startTime = formModel.tradeDate?.[0]?.format('YYYY-MM-DD')
    const endTime = formModel.tradeDate?.[1]?.format('YYYY-MM-DD')
    const { data } = await getRechargeList({
      param: { ...formModel, startTime, endTime },
      page: {
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
      },

    })

    dataSource.value = data.data ?? []
    totalNum.value = data?.pageInfo.total
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}
function handleChange(value) {
  console.log(`selected ${value}`)
}
function handleBlur() {
  console.log('blur')
}
function handleFocus() {
  console.log('focus')
}
function filterOption(input, option) {
  return option.label.toLowerCase().includes(input.toLowerCase())
}
// 搜索
async function onSearch() {
  pagination.current = 1
  await init()
  await getTotal()
}
// 导出
async function exportExcel(record) {
  if (loading.value)
    return
  loading.value = true
  try {
    const { data } = await exportCard(record.id)
    if (data.url) {
      window.location.href = data.url
    }
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}

// 重置
async function onReset() {
  formModel.tradeDate = void 0
  formModel.subAppId = void 0
  await init()
}
function handleSizeChange(e) {
  tableSize.value[0] = e.key
}
function filterAction(value) {
  return columns.value.filter((item) => {
    if (value.includes(item.dataIndex))
      return true

    return false
  })
}
const filterColumns = ref(filterAction(getCheckList.value))
watch(
)
const expand = ref(false)
</script>

<template>
  <page-container>
    <a-card mb-4>
      <a-form :model="formModel" layout="inline">
        <a-form-item name="tradeDate" label="查询日期">
          <a-range-picker v-model:value="formModel.tradeDate" allow-clear style="width:250px" />
        </a-form-item>
        <a-form-item name="subAppId" label="充值渠道">
          <a-select
            v-model:value="formModel.subAppId"
            allow-clear
            show-search
            placeholder="请输入关键字搜索"
            style="width: 250px"
            :options="options"
            :filter-option="filterOption"
            @focus="handleFocus"
            @blur="handleBlur"
            @change="handleChange"
          />
        </a-form-item>
        <a-form-item>
          <a-space flex justify-end w-full>
            <a-button type="primary" @click="onSearch">
              <SearchOutlined />查询
            </a-button>
            <a-button @click="onReset">
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
      <div class="mt-5 font-600" style="background:#f5f5f5;padding:10px;margin-bottom:-8px;">
        总充值笔数： <span>{{ totalInfo.rechargeCount ? totalInfo.rechargeCount : 0 }}</span>    &nbsp; &nbsp; &nbsp;充值总金额： <span>{{ totalInfo.rechargeFee ? totalInfo.rechargeFee : 0 }}</span>
      </div>
    </a-card>

    <a-card>
      <a-table bordered :loading="loading" :columns="filterColumns" :scroll="{ x: 1000 }" :data-source="dataSource" :pagination="pagination">
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'faceAmount'">
            <span>{{ Number(record.faceAmount).toFixed(2) }}</span>
          </template>
          <template v-else-if="column.dataIndex === 'useAppNameList'">
            {{ handleHospital(record.useAppNameList) }}
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <div class="action flex flex-center">
              <a @click="handleView(record)">查看</a>
              <span class="middle-line">|</span>
              <a @click="exportExcel(record)">导出</a>
            </div>
          </template>
        </template>
      </a-table>
    </a-card>
  </page-container>
</template>

    <style lang="less" scoped>
      :deep(.ant-btn){
        padding: 4px 8px;
      }
      .ant-divider-horizontal{
        margin: 15px 0;
      }
      .line{
        color:#1677ff;
      }
      .userTitle{
        color:gray;
        width: 100%;
        padding:5px 0;
        border-bottom:1px solid #f1eded;
        margin-bottom: 20px;
      }
      .red{
        color:red;
        /* color:#ff4d4f; */
      }
      .card-title{
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        flex: auto;
        color: rgba(0, 0, 0, 0.88);
        font-weight: 600;
        font-size: 16px;
        line-height: 1.5;
      }
    @media screen and (max-width: 1200px) and (min-width: 992px) {
      .activeCard {
        margin-bottom: 24px;
      }
      .members {
        margin-bottom: 0;
      }
      .extraContent {
        margin-left: -44px;
        .statItem {
          padding: 0 16px;
        }
      }
    }

    @media screen and (max-width: 992px) {
      .activeCard {
        margin-bottom: 24px;
      }
      .members {
        margin-bottom: 0;
      }
      .extraContent {
        float: none;
        margin-right: 0;
        .statItem {
          padding: 0 16px;
          text-align: left;
          &::after {
            display: none;
          }
        }
      }
    }

    @media screen and (max-width: 768px) {
      .extraContent {
        margin-left: -16px;
      }
      .projectList {
        .projectGrid {
          width: 50%;
        }
      }
    }

    @media screen and (max-width: 576px) {
      .pageHeaderContent {
        display: block;
        .content {
          margin-left: 0;
        }
      }
      .extraContent {
        .statItem {
          float: none;
        }
      }
    }

    @media screen and (max-width: 480px) {
      .projectList {
        .projectGrid {
          width: 100%;
        }
      }
    }
    </style>

    <style>
      [class^="ant-checkbox-group"] [class*=" ant-checkbox-group"]{
        margin:10px !important;
        width:190px !important;
      }
</style>
